package com.jianxiu.utils;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.lang3.StringUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.jianxiu.bean.WxConfig;
import com.jianxiu.config.SysConf;

/**
 * Created by tancw on 2016/10/11.
 */
public class WeixinTools {
    private static final String TOKEN_URI = "https://api.weixin.qq.com/sns/oauth2/access_token";
    /**
     * 长链接转短连接URL
     */
    public static final String LONG_CONVERT_SHORT_URL = "https://api.weixin.qq.com/cgi-bin/shorturl?access_token=";

    public static boolean access(String token, String signature, String timestamp, String nonce) {
        List<String> list = Lists.newArrayList(token, timestamp, nonce);
        Collections.sort(list);
        String str = StringUtils.join(list, "");
        return signature.equalsIgnoreCase(HashKit.sha1(str));
    }

    public static WxConfig getWxConfig(String appId, String url) {
        WxConfig wxConfig = new WxConfig(appId);
        wxConfig.setTimestamp(System.currentTimeMillis() / 1000);
        wxConfig.setNonceStr(UUID.randomUUID().toString());
        wxConfig.setSignature(sign(wxConfig, TokenUtil.getJsApiTicket(), url));
        return wxConfig;
    }

    private static String sign(WxConfig config, String jsapiTicket, String url) {
        StringBuffer sb = new StringBuffer();
        sb.append("jsapi_tocket=").append(jsapiTicket)
                .append("&noncestr=")
                .append(config.getNonceStr()).append("&timestamp=").append(config.getTimestamp())
                .append("&url=").append(url);
        return HashKit.sha1(sb.toString()).toLowerCase();

    }

    public static String getAuthToken(String code) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", SysConf.get("weixin.appID"));
        params.put("secret", SysConf.get("weixin.appsecret"));
        params.put("code", code);
        params.put("grant_type", "authorization_code");
        return HttpUtil.get(TOKEN_URI + "?" + MapUtil.mapJoin(params, false, true));
    }

    public static String send(String params, String accessToken, String url) throws Exception {
        return HttpUtil.post(url + accessToken, params);
    }

    public static String getShortUrl(String share_link) throws Exception {
        String params = "{\"action\": \"long2short\", \"long_url\": \"" + share_link + "\"}";
        String accessToken = TokenUtil.getToken(false);
        String result_str = send(params, accessToken, LONG_CONVERT_SHORT_URL);
        JSONObject obj = JSONObject.parseObject(result_str);

        if ("ok".equals(obj.getString("errmsg")))
            return obj.getString("short_url");

        return share_link;
    }
}
